<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="mode==='add'?'新增组织':'编辑组织'"
    :close-on-click-modal="false"
    width="750px"
    @close="close"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="110px" size="small">
      <el-form-item label="父级：" class="is-required">
        <el-cascader
          v-model="parentIds"
          clearable
          :props="{expandTrigger: 'hover',label:'name',value:'id', checkStrictly: true }"
          placeholder="不选默认为根节点"
          :options="parentOptions"
          @change="handleParentIdChange"
        />
      </el-form-item>
      <el-form-item label="组织名称：" prop="name">
        <el-input v-model="form.name" maxlength="10" show-word-limit placeholder="请输入" />
      </el-form-item>
      <el-form-item label="排序：" prop="ranking">
        <el-input v-model="form.ranking" maxlength="4" show-word-limit placeholder="请输入（数字越小排序越前）" />
      </el-form-item>
      <el-form-item label="描述：" prop="remark">
        <el-input v-model="form.remark" maxlength="15" show-word-limit placeholder="请输入" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" :disabled="loading" round @click="hide">取 消</el-button>
      <el-button size="small" :disabled="loading" round type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addOrg, updateOrg } from '@/api/user/organization'
import { menusTreeToList, findTreeParent } from '@/utils/menus'
import { validCustomPositiveInt } from '@/utils/validate'

export default {
  data() {
    // 校验方法
    // 排序
    const validateRanking = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback()
      } else if (!validCustomPositiveInt(value, 4, [0])) {
        callback(new Error('请输入整数'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        name: { required: true, message: '请输入组织名称', trigger: ['blur', 'change'] },
        ranking: [
          {
            required: false,
            validator: validateRanking,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      title: null,
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      mode: 'add',
      parentOptions: [],
      parentIds: [],
      form: {
        name: null,
        parentId: -1,
        ranking: null,
        remark: null
      }
    }
  },
  computed: {},
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open({ mode = 'add', parentId = -1, treeList = [], row = null }) {
      console.log(parentId)
      this.mode = mode
      this.form.parentId = parentId
      this.parentOptions = treeList
      if (row) this.form = Object.assign({}, row)
      this.findParentIds()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.parentIds = []
      this.form = {
        name: null,
        parentId: -1,
        ranking: null,
        remark: null
      }
      this.$refs.form.resetFields()
      this.loading = false
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const params = Object.assign({}, this.form)
          params.parentId = params.parentId === -1 ? 0 : params.parentId
          const apiFun = this.mode === 'add' ? addOrg : updateOrg
          apiFun({ data: params }).then(() => {
            this.$notify({
              title: '成功',
              message: this.mode === 'add' ? '新增成功' : '更新成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve(params)
            this.hide()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    /**
     * 数据组
     */
    // 找父节点
    findParentIds() {
      if (this.form.parentId && this.form.parentId !== -1) {
        const parentList = menusTreeToList(this.parentOptions)
        const currentList = findTreeParent(parentList, this.form.parentId)
        const parentIds = [-1]
        for (let i = 0; i < currentList.length; i++) {
          parentIds.push(currentList[i].id)
        }
        this.parentIds = parentIds
      } else {
        this.parentIds = [-1]
      }
    },
    /**
     * 按钮组
     */

    /**
     * 状态组
     */
    // 父级变化
    handleParentIdChange(value) {
      if (value && value.length > 0) {
        this.form.parentId = value[value.length - 1]
      } else {
        this.form.parentId = -1
      }
    }
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/*reset*/
.el-cascader {
  width: 100%;
}
</style>
